import os
from image_processor import ImageProcessor
from video_processor import VideoProcessor
from image_stats import MediaStats

def process_file(file_path, processor_class, stats_method):
    """处理单个文件的通用函数"""
    try:
        processor = processor_class(file_path)
        processor.process()
        stats_method(file_path)
    except Exception as e:
        print(f"处理文件失败 {file_path}: {str(e)}")

def main():
    """主程序入口"""
    try:
        media_dir = 'D:/360MoveData/Users/Hao_MateBook/Desktop/python/照片'
        print(f'开始扫描目录: {media_dir}')
        
        if not os.path.exists(media_dir):
            print(f'错误：目录 "{media_dir}" 不存在！')
            return
            
        # 支持的媒体格式
        image_extensions = ('.jpg', '.jpeg', '.tiff', '.nef', '.cr2', '.png', '.bmp')
        video_extensions = ('.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv')
        
        # 创建统计对象
        stats = MediaStats(media_dir)
        
        # 第一次遍历：重命名所有文件
        print("\n=== 开始重命名文件 ===")
        for root, dirs, files in os.walk(media_dir):
            for file in files:
                try:
                    file_lower = file.lower()
                    file_path = os.path.join(root, file)
                    
                    if file_lower.endswith(image_extensions):
                        processor = ImageProcessor(file_path)
                        processor.rename_file()
                    elif file_lower.endswith(video_extensions):
                        processor = VideoProcessor(file_path)
                        processor.rename_file()
                except Exception as e:
                    print(f"重命名文件失败 {file}: {str(e)}")
        
        # 第二次遍历：处理文件并统计
        print("\n=== 开始处理媒体文件信息 ===")
        for root, dirs, files in os.walk(media_dir):
            if 'temp' in root:  # 跳过temp目录
                continue
                
            print(f'扫描子目录: {root}')
            for file in files:
                try:
                    file_lower = file.lower()
                    file_path = os.path.join(root, file)
                    
                    if file_lower.endswith(image_extensions):
                        print(f'找到图片文件: {file}')
                        process_file(file_path, ImageProcessor, stats.add_image)
                    elif file_lower.endswith(video_extensions):
                        print(f'找到视频文件: {file}')
                        process_file(file_path, VideoProcessor, stats.add_video)
                except Exception as e:
                    print(f"处理文件失败 {file}: {str(e)}")
        
        # 打印统计信息
        stats.print_stats()
        
        # 整理文件到日期目录
        stats.organize_files()
        
    except Exception as e:
        print(f"程序运行出错: {str(e)}")

if __name__ == "__main__":
    main() 